'use strict';
const axios = require('axios')
const urlJoin = require('url-join')
const semver = require('semver')
function getNpmInfo(npmName,registry) {
    if(!npmName){
        return null
    }
    const newRegistry = registry || getDefaultRegistry()
    const npmInfoUrl = urlJoin(newRegistry,npmName)
    return axios.get(npmInfoUrl).then(res=>{
        if(res.status === 200){
            return res.data
        }
    }).catch(err=>{
        return Promise.reject(err)
    })
}
async function getVersion(npmName,registry){
    let data = await getNpmInfo(npmName,registry)
    if(data.versions){
        return Object.keys(data.versions)
    }else{
        return []
    }
}
function getSemverVersions(baseVersion,versions){
    return versions
        .filter(version=>semver.satisfies(version,`>=${baseVersion}`))
        .sort((a,b)=>semver.gt(b,a))
}
async function getNpmSemverVersion(baseVersion,npmName,registry){
    const versions = await getVersion(npmName,registry)
    const newVersion = getSemverVersions(baseVersion,versions)
    if(newVersion && newVersion.length > 0){
        return newVersion[0]
    }
    return null
}

function getDefaultRegistry(isOriginal=false){
    return isOriginal ? 'https://registry.npm.org' : 'https://registry.npmmirror.com'
}
async function getNpmLatesVersion(npmName,registry){
    let versions = await getVersion(npmName,registry)
    if(versions){
        versions = versions.sort((a,b)=>semver.gt(b,a))
        return versions[0]
    }
    return null
}

module.exports = {
    getNpmInfo,
    getVersion,
    getNpmSemverVersion,
    getDefaultRegistry,
    getNpmLatesVersion
}


















